package com.xjtucrafter.kiwi.items.dao.impl;

import com.xjtucrafter.kiwi.items.bean.Item;
import com.xjtucrafter.kiwi.items.dao.ItemDao;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import java.util.List;

/**
 * User: Dash
 * Date: 4/19/16 Time: 9:22 PM
 */

@Repository("itemDao")
public class ItemDaoImpl implements ItemDao {
    @PersistenceContext(name = "unitName")
    private EntityManager entityManager;

    @Override
    public int itemAdd(Item item) {
        entityManager.persist(item);
        return item.getItemID();
    }

    @Override
    public Item itemQuery(String itemName) throws NoResultException{
        String jpql = "select item from Item item where item.itemName=:itemName";
        Item item = (Item) entityManager.createQuery(jpql)
                .setParameter("itemName", itemName)
                .getSingleResult();
        return item;
    }

    @Override
    public List<Item> itemBatchQuery() throws NoResultException{
        String jpql = "select item from Item item";
        List<Item> itemList = entityManager.createQuery(jpql)
                .getResultList();
        return itemList;
    }

    @Override
    public int itemDelete(int itemID) {
        String jpql = "delete from Item item where item.itemID=:itemId";
        int result = entityManager.createQuery(jpql)
                .setParameter("itemId", itemID)
                .executeUpdate();
        return result;
    }

    @Override
    public int itemUpdate(Item item) {
        String jpql = "update Item item set " +
                "item.itemName=:name," +
                "item.itemPrice=:price," +
                "item.itemBelong=:belong," +
                "item.itemPicUrl=:picUrl," +
                "item.itemDesc=:des where item.itemID =:id";
        int result = entityManager.createQuery(jpql)
                .setParameter("name", item.getItemName())
                .setParameter("price", item.getItemPrice())
                .setParameter("belong", item.getItemBelong())
                .setParameter("picUrl", item.getItemPicUrl())
                .setParameter("des",item.getItemDesc())
                .setParameter("id",item.getItemID())
                .executeUpdate();
        return result;
    }
}
